import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/auth'
import Login from '../views/login'
import Home from '../views/home'
import Welcome from '../views/Welcome.vue'
import Users from '../views/users/users.vue'
import Rights from '../views/power/Rights.vue'
import Roles from '../views/power/Roles.vue'

Vue.use(VueRouter)

const constantRoutes = [
  { path: '/', redirect: '/home' },
  { path: '/login', name: 'Login', component: Login },
  {
    path: '/home',
    name: 'Home',
    redirect: '/welcome',
    component: Home,
    children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles }
    ]
  }
]

const createRouter = () => new VueRouter({
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

const router = createRouter()

router.beforeEach((to, from, next) => {
  // 如果用户访问登录页面，直接放行
  if (to.path === '/login') return next()
  // 从sessionStorage获取保存的token值
  const token = getToken()
  // 没有token，就强制跳回登录页面
  if (!token) return next('/login')
  next()
})

export function resetRouter () {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router
